package com.atguigu.ticket;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ticket{
    private int number=50;
    /* 用synchronized锁
    public synchronized void sale(){
        if (number>0){
            System.out.println(Thread.currentThread().getName()+"...买了第"+number--+"张票,还剩"+number+"张票");
        }
    }*/
    private final Lock lock =new ReentrantLock();// ReentrantLock 默认悲观锁,非公平锁效率高,效率优先(false)
    public void sale(){
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "...买了第" + number-- + "张票,还剩" + number + "张票");
            }
        }finally{
                lock.unlock();
            }
        }
}
public class Saleticke {
    public static void main(String[] args) {
        ticket ticket = new ticket();
        new Thread(()-> {for (int i = 0; i <= 50; i++) ticket.sale();}, "李四").start();
        new Thread(()-> {for (int i = 0; i <= 50; i++) ticket.sale();}, "王五").start();
        new Thread(()-> {for (int i = 0; i <= 50; i++) ticket.sale();}, "张三").start();
    }
}
